package com.kasax.plugin.app.visitor.injectTime

import com.kasax.plugin.app.LogUtils
import org.objectweb.asm.ClassVisitor
import org.objectweb.asm.MethodVisitor
import org.objectweb.asm.Opcodes


class ClassInjectTimeVisitor extends ClassVisitor {
    private final String TAG = "ClassInjectTimeVisitor"
    private String mClsName

    ClassInjectTimeVisitor(ClassVisitor classVisitor) {
        super(Opcodes.ASM7, classVisitor)
    }

    @Override
    void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
        super.visit(version, access, name, signature, superName, interfaces)
        this.mClsName = name
        LogUtils.d(TAG, "visit clsName : $mClsName")
    }

    @Override
    MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions) {
        LogUtils.d(TAG, "visitMethod : $name start....")
        def mv = super.visitMethod(access, name, descriptor, signature, exceptions)
        // 确保所有方法都有返回
        if (mv == null) {
            LogUtils.d(TAG, "visitMethod : $name complete1....")
            return null
        }
        def isSupported = isSupportedCls()
        LogUtils.d(TAG, "visitMethod isSupported: $isSupported")
        if (isSupported) {
            if ("onCreate".equals(name)) {
                LogUtils.d(TAG, "visitMethod : $name , exec LifecycleOnCreateMethodVisitor2")
                // 处理onCreate方法
                LogUtils.d(TAG, "visitMethod : $name complete2....")
                return new TimeMethodVisitor(mv)
            }
        }
        LogUtils.d(TAG, "visitMethod : $name complete3....")
        return mv
    }

    private boolean isSupportedCls() {
        this.mClsName != null && (this.mClsName.equals("android/support/v4/app/FragmentActivity") ||
                this.mClsName.equals("androidx.appcompat.app.AppCompatActivity") ||
                this.mClsName.startsWith("com/kasax/"))
    }

    @Override
    void visitEnd() {
        LogUtils.d(TAG, "visitEnd")
        super.visitEnd()
    }
}